/*
 * @Author: worldzb 
 * @Date: 2019-01-08 10:41:32 
 * @Last Modified by: worldzb
 * @Last Modified time: 2019-01-08 13:04:51
 */

//该文件用于对 axios 添加拦截器，以便用来实现每次
//请求的 token 添加，从而实现接口调用鉴权等等

import axios from 'axios';
import Auth from '../store/modules/auth';

// http request 拦截器
axios.interceptors.request.use(
    config => {
        if (localStorage.getItem('token')) {  //判断是否存在token，如果存在的话，则每个http header都加上token
            config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`;
        }
        return config;
    },
    err => {
        return Promise.reject(err);
    }
);

// http response 拦截器
axios.interceptors.response.use(
    response => {
        console.log('拦截',response);
        return response;
    },
    error => {
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    const auth = new Auth();
                    auth.refresh();
            }
        }
        return Promise.reject(error.response.data)   // 返回接口返回的错误信息
    }
);

export default axios;
